package tw.com.hitevision.whiteboard.android.andServer;

import android.util.Log;

import com.yanzhenjie.andserver.RequestHandler;
import com.yanzhenjie.andserver.RequestMethod;
import com.yanzhenjie.andserver.annotation.RequestMapping;

import org.apache.httpcore.HttpEntity;
import org.apache.httpcore.HttpException;
import org.apache.httpcore.HttpRequest;
import org.apache.httpcore.HttpResponse;
import org.apache.httpcore.entity.ContentType;
import org.apache.httpcore.entity.FileEntity;
import org.apache.httpcore.protocol.HttpContext;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

import static com.yanzhenjie.andserver.util.FileUtils.getMimeType;

public class DownloadPDFHandler implements RequestHandler {

    private String TAG = DownloadPDFHandler.class.getSimpleName();
    private File file;

    DownloadPDFHandler(File file) {
        this.file = file;
    }

    @RequestMapping(method = {RequestMethod.GET})
    @Override
    public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
        Log.d(TAG, "file path:" + file.getAbsolutePath());
        HttpEntity entity = new FileEntity(file, ContentType.create(getMimeType(file.getAbsolutePath()), Charset.defaultCharset()));
        response.setHeader("Content-Disposition", "attachment;filename=download.pdf");
        response.setStatusCode(200);
        response.setEntity(entity);
    }
}
